package com.taxshare.manager.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.manager.constant.ResultConstant;
import com.taxshare.manager.entity.OrganizeEntity;
import com.taxshare.manager.entity.UserOrganizeEntity;
import com.taxshare.manager.mapper.OrganizeMapper;
import com.taxshare.manager.mapper.UserOrganizeMapper;
import com.taxshare.manager.view.dto.OrganizeDTO;
import com.taxshare.manager.view.vo.OrganizeVO;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: OrganizeService
 * @Description:
 * @author: luozhongyi
 * @date: 2021/2/3 14:26
 */
@Service
public class OrganizeService extends ServiceImpl<OrganizeMapper, OrganizeEntity> {

    @Autowired
    UserOrganizeMapper userOrganizeMapper;
    @Autowired
    OrganizeMapper organizeMapper;

    /**
     * 初始化组织管理
     *
     * @return
     */
    public Response initOrgTree() {
        //获取当前用户类型
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        List<OrganizeEntity> organizeEntities = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(organizeEntities)) {
            return Response.success(organizeEntities);
        }
        List<OrganizeVO> resourceVOList = JSONUtil.toList(JSONUtil.parseArray(organizeEntities), OrganizeVO.class);
        //构造菜单树
        Map<String, OrganizeVO> dataMap = new HashMap<>(resourceVOList.size() * 4 / 3 + 1);
        for (OrganizeVO bean : resourceVOList) {
            dataMap.put(bean.getOrgId(), bean);
        }
        //构造Tree
        List<OrganizeVO> treeList = new ArrayList<>(30);
        for (OrganizeVO bean : resourceVOList) {
            //如果父节点为0,则表示其为根节点
            if ("0".equals(bean.getOrgPid())) {
                treeList.add(bean);
            } else {
                //获取父节点所在的对象
                OrganizeVO parentEntity = dataMap.get(bean.getOrgPid());
                //如果为null则表明此节点的父节点不存在了
                if (parentEntity != null) {
                    //将其存放到父节点的children属性下
                    parentEntity.getChildren().add(bean);
                }
            }
        }
        return Response.success(treeList);
    }

    /**
     * 新增组织
     *
     * @param organizeDTO
     * @return
     */
    public Response add(OrganizeDTO organizeDTO) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_name", organizeDTO.getOrgName());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_O0001_CODE, ResultConstant.RET_O0001_MSG);
        }
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_code", organizeDTO.getOrgCode());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_O0002_CODE, ResultConstant.RET_O0002_MSG);
        }
        if (StrUtil.isNotBlank(organizeDTO.getCompanyName())) {
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("company_name", organizeDTO.getCompanyName());
            queryWrapper.ne("org_id", organizeDTO.getOrgId());
            if (baseMapper.selectCount(queryWrapper) > 0) {
                return Response.error(ResultConstant.RET_O0003_CODE, ResultConstant.RET_O0003_MSG);
            }
        }
        if (StrUtil.isNotBlank(organizeDTO.getCompanyTaxnumber())) {
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("company_tax_number", organizeDTO.getCompanyTaxnumber());
            queryWrapper.ne("org_id", organizeDTO.getOrgId());
            if (baseMapper.selectCount(queryWrapper) > 0) {
                return Response.error(ResultConstant.RET_O0004_CODE, ResultConstant.RET_O0004_MSG);
            }
        }
        //如果组织类型未纳税主体则税号不能为空
        String orgId = UUIDUitl.UUID32();
        OrganizeEntity entity = DozerBeanUtil.map(organizeDTO, OrganizeEntity.class);
        entity.setOrgId(orgId);
//        if (StrUtil.hasBlank(entity.getOrgPid())) {
//            entity.setOrgPid("0");
//        }
        // 如果 orgPid 为 0，设置为默认值
        if ("0".equals(organizeDTO.getOrgPid())) {
            entity.setOrgPid("0"); // 或者根据你的逻辑设置为其他值
        } else {
            entity.setOrgPid(organizeDTO.getOrgPid()); // 使用传入的 orgPid
        }
        this.save(entity);
        //自动关联组织信息
        if (CommonConstant.AUTH_TYPE_2.equals(UserInfoUtil.getUserType()) || CommonConstant.AUTH_TYPE_1.equals(UserInfoUtil.getUserType())) {
            UserOrganizeEntity userOrganizeEntity = new UserOrganizeEntity();
            userOrganizeEntity.setUuid(UUIDUitl.UUID32());
            userOrganizeEntity.setOrgId(orgId);
            userOrganizeEntity.setUserId(UserInfoUtil.getUserID());
            userOrganizeMapper.insert(userOrganizeEntity);
        }
        return Response.success();
    }

    /**
     * 编辑组织
     *
     * @param organizeDTO
     * @return
     */
    public Response edit(OrganizeDTO organizeDTO) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_name", organizeDTO.getOrgName());
        queryWrapper.ne("org_id", organizeDTO.getOrgId());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_O0001_CODE, ResultConstant.RET_O0001_MSG);
        }
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_code", organizeDTO.getOrgCode());
        queryWrapper.ne("org_id", organizeDTO.getOrgId());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_O0002_CODE, ResultConstant.RET_O0002_MSG);
        }
        if (StrUtil.isNotBlank(organizeDTO.getCompanyName())) {
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("company_name", organizeDTO.getCompanyName());
            queryWrapper.ne("org_id", organizeDTO.getOrgId());
            if (baseMapper.selectCount(queryWrapper) > 0) {
                return Response.error(ResultConstant.RET_O0003_CODE, ResultConstant.RET_O0003_MSG);
            }
        }
        if (StrUtil.isNotBlank(organizeDTO.getCompanyTaxnumber())) {
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("company_tax_number", organizeDTO.getCompanyTaxnumber());
            queryWrapper.ne("org_id", organizeDTO.getOrgId());
            if (baseMapper.selectCount(queryWrapper) > 0) {
                return Response.error(ResultConstant.RET_O0004_CODE, ResultConstant.RET_O0004_MSG);
            }
        }
        OrganizeEntity entity = DozerBeanUtil.map(organizeDTO, OrganizeEntity.class);
        return Response.success(this.updateById(entity));
    }

    /**
     * 删除组织
     *
     * @param organizeDTO
     * @return
     */
    public Response delete(OrganizeDTO organizeDTO) {
        //如果当前节点存在子节点则无法删除
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_pid", organizeDTO.getOrgId());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_O0005_CODE, ResultConstant.RET_O0005_MSG);
        }
        queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_id", organizeDTO.getOrgId());
        baseMapper.delete(queryWrapper);
        //删除用户于组织的关联关系
        UpdateWrapper<UserOrganizeEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("org_id", organizeDTO.getOrgId());
        userOrganizeMapper.delete(updateWrapper);
        return Response.success();
    }

    /**
     * 查询组织
     *
     * @param orgId
     * @return
     */
    public Response info(String orgId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.like("org_id", orgId);
        OrganizeEntity entity = this.getOne(queryWrapper);
        return Response.success(entity);
    }

    /**
     * 账套管理展示公司列表分页查询
     *
     * @param query
     * @return
     */
    public Response queryOrganizeEntityList(PageRequest<OrganizeEntity> query) {

        // 创建 MyBatis-Plus 的 Page 对象
        Page<OrganizeEntity> page = new Page<>(query.getPage().getCurrentPage(), query.getPage().getPageSize());

        // 创建 QueryWrapper
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_pid", "0"); // 默认查询条件

        // 根据需要添加其他过滤条件
        OrganizeEntity organizeEntity = query.getInfo();
        if (organizeEntity != null) {
            if (StrUtil.isNotBlank(organizeEntity.getCompanyName())) {
                queryWrapper.eq("company_name", organizeEntity.getCompanyName());
            }
            if (StrUtil.isNotBlank(organizeEntity.getCompanyTaxNumber())) {
                queryWrapper.eq("company_tax_number", organizeEntity.getCompanyTaxNumber());
            }
        }

        // 执行分页查询
        IPage<OrganizeEntity> resultPage = organizeMapper.selectPage(page, queryWrapper);
        List<OrganizeEntity> list = resultPage.getRecords();
        for (OrganizeEntity organize : list){
            String nsrsbh = organize.getCompanyTaxNumber();
            Map<String,Object> map = organizeMapper.selectSxEd(nsrsbh);
            organize.setSxEd(MapUtils.getString(map,"kysyed",""));
        }
        // 返回结果
        return Response.success(resultPage);
    }

    /**
     * 根据公司税号查授信额度管理列表
     *
     * @param taxNumber
     * @return
     */
    public OrganizeEntity getOrganizeByTaxNumber(String taxNumber) {
        return organizeMapper.findOrganizeByTaxNumber(taxNumber);
    }

    /**
     * 根据父公司id查子公司的对应列表
     *
     * @param orgPid
     * @return
     */
    public Response queryCompanyName(String orgPid) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("org_pid ", orgPid);
        // 查询子公司
        List<OrganizeEntity> subCompanies = organizeMapper.selectList(queryWrapper);
        return Response.success(subCompanies);
    }

    /**
     * 账套修改
     *
     * @param entity
     * @return
     */
    public Response updateOrganize(OrganizeEntity entity) {
        entity.setUpdateUserid(UserInfoUtil.getUserID());
        baseMapper.updateById(entity);
        return Response.success();
    }


    public OrganizeEntity getOrganizeTaxList(String taxNumber) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_tax_number ", taxNumber);
        return organizeMapper.selectOne(queryWrapper);
    }

}
